/*
*    Phantom Test Driver v2.0 GUI Automation Software
*    Copyright (C) 2009  John C. Van Arsdall (john@phantomtest.com)
*
*    This program is free software; you can redistribute it and/or modify
*    it under the terms of the GNU General Public License as published by
*    the Free Software Foundation; either version 2 of the License, or
*    (at your option) any later version.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU General Public License for more details.
*
*    You should have received a copy of the GNU General Public License along
*    with this program; if not, write to the Free Software Foundation, Inc.,
*    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ptd;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import ssi_xml.SSIXml;
import ssi_xml.SSIXml.myXMLException;

/**
 *
 * @author John
 */
public class PTDWorkspace {
    public String FileName;
    public Vector<String> OpenScripts;
    public String OpenSuite;
    public Vector<String> OpenDecls;
    public Vector<PTDRemoteMachine> Machines;
    
    private final String tag_PTD = "PTD_workspace";
    private final String tag_Scripts = "Open_Scripts";
    private final String tag_Suite = "Open_Suite";
    private final String tag_Decls = "Open_Decls";
    private final String tag_Machines = "Remote_Agents";
    private final String tag_Script = "Script";
    private final String tag_Decl = "Decl";
    private final String tag_Machine = "Agent";
    
    private final String PORT_SEP = ":";
    
    
    public PTDWorkspace(){
        OpenScripts = new Vector<String>();
        OpenSuite = "";
        FileName = "";
        OpenDecls = new Vector<String>();
        Machines = new Vector<PTDRemoteMachine>();
        
    }
    
    public boolean saveData(PTDMain Input, boolean bForceNew){
        OpenScripts.clear();
        OpenSuite = "";
        OpenDecls.clear();
        
        if(!getOpenScripts(Input)){
            return false;
        }
        if(!getOpenDecls(Input)){
            return false;
        }
        if(!getOpenSuite(Input)){
            return false;
        }

        
        try {
            SSIXml Root = new SSIXml(tag_PTD);
            SSIXml Suite = Root.addElement(tag_Suite, OpenSuite);
            SSIXml Scripts = Root.addElement(tag_Scripts);
            SSIXml Decls = Root.addElement(tag_Decls);
            SSIXml Agents = Root.addElement(tag_Machines);
            
        
            for(int ctr = 0; ctr < OpenScripts.size(); ctr++){
                Scripts.addElement(tag_Script, OpenScripts.get(ctr));
            }

            for(int ctr = 0; ctr < OpenDecls.size(); ctr++){
                Decls.addElement(tag_Decl, OpenDecls.get(ctr));
            }

            for(int ctr = 0; ctr < Machines.size(); ctr++){
                Agents.addElement(tag_Machine, Machines.get(ctr).myName + PORT_SEP + Integer.toString(Machines.get(ctr).myPort));
            }            
            
            if(FileName.length() == 0 || bForceNew){
                if(requestFileName(JFileChooser.SAVE_DIALOG) == false){
                    return false;
                }
            }
            
            PrintWriter pw = new PrintWriter(FileName);
            Root.serialize(pw);
            pw.close();
            Input.setWorkspaceTitle(FileName);
            
        } catch (Exception ex) {
            Main.debug_out(ex.getMessage());
        }
        return true;
    }

    public void loadData(PTDMain Input){
        
        OpenScripts.clear();
        OpenSuite = "";
        OpenDecls.clear();
        Machines.clear();
        
       
  

            if(FileName.length() == 0){
                if(requestFileName(JFileChooser.OPEN_DIALOG) == false){
                    return;
                }
            }
        
            
            SSIXml Root = null;
            try {
                File F = new File(FileName);
                BufferedReader Buf = new BufferedReader(new FileReader(FileName));            
                Root = new SSIXml(Buf);
                Buf.close();
            } catch (Exception ex) {
                Main.debug_out(ex.getMessage());
                PTDMessageBox.MessageBox("Workspace not found: " + FileName);
                return;
            }
        
            SSIXml Suite = Root.findElement(tag_Suite);
            SSIXml Scripts = Root.findElement(tag_Scripts);
            SSIXml Decls = Root.findElement(tag_Decls);
            SSIXml Agents = Root.findElement(tag_Machines);
         
            if(Suite != null){
                OpenSuite = Suite.getValue();
            }
            
            if(Scripts != null){
                for(int i = 0; i < Scripts.size(); i++){
                    SSIXml Script = Scripts.getElement(i);
                    if(Script != null){
                        OpenScripts.add(Script.getValue());
                    }
                }
            }
            
            if(Decls != null){
                for(int i = 0; i < Decls.size(); i++){
                    SSIXml Decl = Decls.getElement(i);
                    if(Decl != null){
                        OpenDecls.add(Decl.getValue());
                    }
                }
            }

            if(Agents != null){
                for(int i = 0; i < Agents.size(); i++){
                    SSIXml Agent = Agents.getElement(i);
                    if(Agent != null){
                        PTDRemoteMachine M = new PTDRemoteMachine();
                        String s = Agent.getValue();
                        int ind = s.indexOf(PORT_SEP);
                        if(ind > 0){
                            String[] T = s.split(":");
                            if(T.length == 2){
                                M.myName = T[0].trim();
                                M.myPort = Integer.parseInt(T[1].trim());
                                Machines.add(M);
                            }
                        }
                    }
                }
            }
            if(!Input.clearWorkspace()){
                return;
            }
            
            if(!Input.loadDecls(OpenDecls)){
                return;
            }
            if(!Input.loadScripts(OpenScripts)){
                return;
            }
            if(!Input.loadSuite(OpenSuite)){
                return;
            }            
            
            Input.setWorkspaceTitle(FileName);
            
    }
    
    public boolean getOpenScripts(PTDMain Input){
        OpenScripts = Input.getOpenScripts();
        return true;
    }

    public boolean getOpenDecls(PTDMain Input){
        OpenDecls = Input.getOpenDecls();
        return true;
    }

    public boolean getOpenSuite(PTDMain Input){
        OpenSuite = Input.getSuiteFile();
        return true;
    }

    
    public boolean requestFileName(int iType){
        JFileChooser aChooser = new JFileChooser();
        PTDFileFilter psc_filter = new PTDFileFilter("pws", "PTD Workspace (.pws)");
        aChooser.setCurrentDirectory(PTDMain.g_CurrentDir);
        aChooser.addChoosableFileFilter(psc_filter);

        int result = 0;
        if(iType == JFileChooser.SAVE_DIALOG){
            result = aChooser.showSaveDialog(Main.getMainFrame());
        }else if(iType == JFileChooser.OPEN_DIALOG){
            result = aChooser.showOpenDialog(Main.getMainFrame());
        }else{
            return false;
        }
        if(result == JFileChooser.CANCEL_OPTION){
            return false;
        }
        File afile = aChooser.getSelectedFile();
        
        PTDMain.g_CurrentDir = afile.getParentFile();
        
        String sPath = afile.getAbsolutePath();
        String sName = afile.getName();
        if(sName.indexOf('.') < 0){
            sPath = sPath + ".pws";
        }

        if(iType == JFileChooser.SAVE_DIALOG){
            if(afile.exists()){
                JOptionPane anOption = new JOptionPane();
                int o = anOption.showConfirmDialog(null, "File exists. Overwrite?", "Confirm Overwrite", anOption.OK_CANCEL_OPTION);
                if(o == anOption.CANCEL_OPTION){
                    return false;
                }
            }
        }else{
            if(!afile.exists()){
                PTDMessageBox.MessageBox("Workspace file does not exist.");
                return false;
            }
            clear();
        }
        FileName = sPath;
        return true;
    }
    
    public void clear(){
        FileName = "";
        OpenScripts.clear();
        OpenSuite = "";
        OpenDecls.clear();
        Machines.clear();
    }
    
}
